package com.insyte.fragments;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.insyte.R;
import com.insyte.activities.SettingActivity;
import com.insyte.activities.TabMainActivity;
import com.insyte.config.Constants;
import com.insyte.config.InsyteApp;
import com.insyte.model.User;
import com.insyte.utils.Initialize;
import com.insyte.utils.NonSwipeableViewPager;

import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class ProfilePhotoFragment extends Fragment {

    private ImageView btn_Capture, imgShow;
    int REQUEST_CAMERA = 0, SELECT_FILE = 1;
    private Button btn_next;
    private ImageView img_logo_nav, imgBack;
    private NonSwipeableViewPager viewPager;
    private File file_img_created;
    public static final int PICK_FROM_CAMERA = 1;
    public static final int PICK_FROM_GALLERY = 2;
    public static String img_path = "";
    public static Bitmap bitmap;
    private User user;
    private String url_set_profile = Constants.URL_API + "/user/profile/%s";
    private HashMap<String, Object> params;
    private AQuery aQuery;
    private ByteArrayOutputStream baos;
    public static String imageEncoded;
    private ProgressDialog progressDialog;
    private Initialize initialize;
    private String statusMarried = "";
    public ProfilePhotoFragment setViewPager(NonSwipeableViewPager viewPager) {
        this.viewPager = viewPager;
        return this;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_profile_photo, container, false);

        user = InsyteApp.getInstance().getUser();
        initialize = new Initialize(getActivity());
        progressDialog = initialize.createProgressDialog("Loading");
        params = new HashMap<String, Object>();
        aQuery = new AQuery(getActivity());
        baos = new ByteArrayOutputStream();
        btn_Capture = (ImageView) view.findViewById(R.id.btn_Capture);
        imgShow = (ImageView) view.findViewById(R.id.imgShow);
        imgBack = (ImageView) view.findViewById(R.id.imgBack);
        btn_next = (Button) view.findViewById(R.id.btn_next);



        btn_Capture.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showTakeAphoto();
            }
        });
        imgBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                viewPager.setCurrentItem(1);
            }
        });
        btn_next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(new Intent(getActivity(), TabMainActivity.class));
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
                getActivity().finish();
                //setProfile();
            }
        });
        return view;
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public void showTakeAphoto() {
        final CharSequence[] options = {"Take Photo", "Choose from Gallery", "Cancel"};
        AlertDialog.Builder builder = null;
//        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
//            builder = new AlertDialog.Builder(ProfileActivity.this, android.R.style.Theme_Holo_Light_Dialog);
//        } else {
        builder = new AlertDialog.Builder(getActivity(), ProgressDialog.THEME_HOLO_LIGHT);
//        }
        builder.setTitle("Update Photo!");
        builder.setItems(options, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int item) {
                if (options[item].equals("Take Photo")) {
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    String path_save_img = android.os.Environment.getExternalStorageDirectory() + File.separator + "Pictures/Insyte";
                    File new_folder = new File(path_save_img);
                    if (!new_folder.exists()) {
                        new_folder.mkdirs();
                    }
                    String format_img = "IMG_" + System.currentTimeMillis() + ".jpg";
                    if (file_img_created != null) {
                        file_img_created.delete();
                    }
                    file_img_created = new File(path_save_img, format_img);
//                    intent.putExtra(MediaStore.EXTRA_OUTPUT, 1);
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file_img_created));
                    startActivityForResult(intent, 1);
                } else if (options[item].equals("Choose from Gallery")) {
                    Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    intent.setType("image/*");
                    startActivityForResult(Intent.createChooser(intent, "Select File"), 2);
                } else if (options[item].equals("Cancel")) {
                    dialog.dismiss();
                }
            }
        });
        builder.show();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == getActivity().RESULT_OK) {
            if (requestCode == PICK_FROM_CAMERA) {
                resizeQualityImg(file_img_created);
                img_path = file_img_created.getAbsolutePath();
                bitmap = BitmapFactory.decodeFile(img_path);
                imgShow.setImageBitmap(bitmap);
                //convert to base64 string
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
                byte[] b = baos.toByteArray();
                imageEncoded = Base64.encodeToString(b, Base64.DEFAULT);
                Log.e("LOOK", imageEncoded);
            } else if (data != null && data.getData() != null) {
                if (requestCode == PICK_FROM_GALLERY) {
                    try {
                        Uri file_uri = data.getData();
                        createNewFileImg(file_uri);
                        img_path = file_img_created.getAbsolutePath();
                        bitmap = BitmapFactory.decodeFile(img_path);
                        imgShow.setImageBitmap(bitmap);
                        //convert to base64 string
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
                        byte[] b = baos.toByteArray();
                        imageEncoded = Base64.encodeToString(b, Base64.DEFAULT);
                        Log.e("LOOK", imageEncoded);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        } else if (resultCode == getActivity().RESULT_CANCELED) {
            // User cancelled the image capture
        } else {
            // Image capture failed, advise user
        }
    }

    private Bitmap bitmap_img_user;
    public void resizeQualityImg(File f) {
        BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
        bitmapOptions.inJustDecodeBounds = true;
        Bitmap bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(), bitmapOptions);
        bitmapOptions.inSampleSize = calculateInSampleSize(bitmapOptions, 400, 400);
        bitmapOptions.inJustDecodeBounds = false;
        bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(), bitmapOptions);
        try {
            ExifInterface exif = new ExifInterface(f.getAbsolutePath());
            int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
            Log.e("orientation", orientation + "");
            Matrix matrix = rotateImage(null, f);
            bitmap_img_user = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
            ByteArrayOutputStream bytes = new ByteArrayOutputStream();
            int size_quality = 100;
            Log.e("size_quality", size_quality + "");
            bitmap_img_user.compress(Bitmap.CompressFormat.JPEG, size_quality, bytes);
            FileOutputStream fo = new FileOutputStream(f);
            fo.write(bytes.toByteArray());
            fo.flush();
            fo.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void createNewFileImg(Uri photoUri) {
        try {
            BitmapFactory.Options options = new BitmapFactory.Options();
            int orientation = getOrientation(photoUri);
            Matrix matrix = new Matrix();
            switch (orientation) {
                case 270:
                    matrix.postRotate(270);
                    break;
                case 180:
                    matrix.postRotate(180);
                    break;
                case 90:
                    matrix.postRotate(90);
                    break;
            }
            Log.e("orientation__", orientation + "");
            ByteArrayOutputStream bytes = new ByteArrayOutputStream();
            options.inJustDecodeBounds = true;
            Bitmap bitmap_decode = BitmapFactory.decodeStream(getActivity().getContentResolver().openInputStream(photoUri), null, options);
            options.inSampleSize = calculateInSampleSize(options, 400, 400);
            Log.e("inSapleSize", options.inSampleSize + "");
            options.inJustDecodeBounds = false;
            bitmap_decode = BitmapFactory.decodeStream(getActivity().getContentResolver().openInputStream(photoUri), null, options);
            bitmap_img_user = Bitmap.createBitmap(bitmap_decode, 0, 0, bitmap_decode.getWidth(),
                    bitmap_decode.getHeight(), matrix, true);
            // write to bytes
            bitmap_img_user.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
            String path_save_img = android.os.Environment.getExternalStorageDirectory() + File.separator + "Pictures/Insyte";
            String file_img_new = "IMG_" + System.currentTimeMillis() + ".jpg";
            file_img_created = new File(path_save_img, file_img_new);
            file_img_created.createNewFile();
            FileOutputStream fo = new FileOutputStream(file_img_created);
            fo.write(bytes.toByteArray());
            fo.flush();
            fo.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public int getOrientation(Uri photoUri) {
        // it's on the external media. /
        Cursor cursor = getActivity().getContentResolver().query(photoUri,
                new String[]{MediaStore.Images.ImageColumns.ORIENTATION}, null, null, null);
        if (cursor.getCount() != 1) {
            return -1;
        }
        cursor.moveToFirst();
        return cursor.getInt(0);
    }

    public int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        // Raw height and width of image
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;
        if (height > reqHeight || width > reqWidth) {
            final int halfHeight = height / 2;
            final int halfWidth = width / 2;
            // Calculate the largest inSampleSize value that is a power of 2 and keeps both
            // height and width larger than the requested height and width.
            while ((halfHeight / inSampleSize) > reqHeight
                    && (halfWidth / inSampleSize) > reqWidth) {
                inSampleSize *= 2;
            }
        }
        return inSampleSize;
    }

    public Matrix rotateImage(Uri imageUri, File f) {
        Matrix matrix = new Matrix();
        try {
            if (imageUri != null) {
                getActivity().getContentResolver().notifyChange(imageUri, null);
            }
            ExifInterface exif = new ExifInterface(f.getAbsolutePath());
            int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
            Log.e("orientation", orientation + "");
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_270:
                    matrix.postRotate(270);
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    matrix.postRotate(180);
                    break;
                case ExifInterface.ORIENTATION_ROTATE_90:
                    matrix.postRotate(90);
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return matrix;
    }


    private void setProfile()
    {
        String url_setprofile = String.format(url_set_profile,user.getId());
        if(user.getDating_status().equalsIgnoreCase("Married")) {
            statusMarried = "married";
        }
        else if(user.getDating_status().equalsIgnoreCase("single")) {
            statusMarried = "single";
        }
        params.put("token", user.getToken());
        params.put("gender", user.getGender());
        params.put("age",user.getAge());
        params.put("height", user.getHeight());
        params.put("story", user.getStory()+"");
        params.put("dating_status",statusMarried);
        params.put("interests",user.getInterest()+"");
        params.put("profile_picture",imageEncoded);
//        params.put("id",user.getId());
        progressDialog.show();
        aQuery.ajax(url_setprofile, params, String.class, new AjaxCallback<String>() {
            @Override
            public void callback(String url, String result, AjaxStatus status) {
                progressDialog.dismiss();
                if (result != null) {
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        if (jsonObject.has("code")) {
                            String message = jsonObject.getString("message");
                            if (jsonObject.getInt("code") == 1) {
                                initialize.showToast(message);
                                startActivity(new Intent(getActivity(), SettingActivity.class));
                            } else {
                                initialize.showToast(message);
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }.method(AQuery.METHOD_PUT)
                .header("Content-Type", "application/x-www-form-urlencoded"));
        Toast.makeText(getActivity(),user.getDating_status(),Toast.LENGTH_LONG).show();
    }

}
